#include "widget.h"
#include "ui_widget.h"
#include <QBoxLayout>
#include <QTimer>
#include <QCameraImageCapture>
#include <QDesktopWidget>
#include "userdialog.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 视频显示窗口
    viewfinder = new QCameraViewfinder(this);
    viewfinder->setGeometry(this->geometry());
    viewfinder->setAspectRatioMode(Qt::IgnoreAspectRatio);
    viewfinder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    // 添加显示窗口
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(viewfinder);
    this->setLayout(layout);

    // 创建摄像头捕获
    camera = new QCamera(this);
    camera->setViewfinder(viewfinder);
    camera->start();

    // 创建用户信息显示窗口
    userDialog = new UserDialog(NULL);
    userDialog->layout()->setContentsMargins(0, 0, 0, 0);
    userDialog->layout()->setSpacing(0);
    userDialog->setWindowFlags(Qt::FramelessWindowHint);
    //UserDialog->setAttribute(Qt::WA_TranslucentBackground);
    userDialog->setStyleSheet("QWidget{"
                            "border-radius:30px;"
                            "border-style:solid;"
                            "border-width:2px;"
                            "border-color:rgb(213, 213, 213);"
                            "}");
    userDialog->setWindowOpacity(0.65);
    userDialog->setFixedWidth(350);
    userDialog->setFixedHeight(450);

    // 获取屏幕数目
    QDesktopWidget desktop;
    int screenCount = desktop.screenCount();

    // 居中显示窗口
    for (int i = 0; i < screenCount; ++i) {
        QRect screenRect = desktop.availableGeometry(i);
        int x = (screenRect.width() - userDialog->width()) / 2 + screenRect.x();
        int y = (screenRect.height() - userDialog->height()) / 2 + screenRect.y();
        userDialog->move(x, y);
    }

    // 图片抓拍线程
    captureThread = new CaptureThread(camera);
    captureThread->start();

    // 图片抓拍事件
    connect(captureThread, &CaptureThread::capture, [=](int id, QImage img){
        QString name = QString("第%1张图片").arg(id);
        userDialog->setUser(name, img);
        userDialog->show();
        userDialog->raise();
    });
}

Widget::~Widget()
{
    // 停止抓拍线程
    if (captureThread && captureThread->isRunning()){
        captureThread->SetRun(false);
        captureThread->wait();
        captureThread->quit();
    }
    // 停止摄像头
    if (camera) {
        camera->stop();
    }
    // 删除用户窗口
    delete userDialog;
    delete ui;
}
